﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

/// <summary>
/// JsonHelper 的摘要描述
/// </summary>
/// 
namespace com.pro2e.web.util
{

    public class JsonHelper
    {
        #region DataContractJsonSerializer

        /// <summary>
        /// 對象轉換成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObject">需要格式化的物件</param>
        /// <returns>Json字串</returns>
        public static string DataContractJsonSerialize<T>(T jsonObject)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = null;
            using (MemoryStream ms = new MemoryStream()) //定義一個stream用來存發序列化之後的內容
            {
                serializer.WriteObject(ms, jsonObject);
                json = Encoding.UTF8.GetString(ms.GetBuffer()); //將stream讀取成一個字串形式的資料，並且返回
                ms.Close();
            }
            return json;
        }

        /// <summary>
        /// json字串轉換成物件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json">要轉換成物件的json字串</param>
        /// <returns></returns>
        public static T DataContractJsonDeserialize<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }

        #endregion

    }
}
